const {
    ad,
    statistics,
    hotlist,
    hotMerchants,
    merchantsType,
    messageType,
    addtype,
    recotribelist,
    tribetopiclist
} = require('../../utils/api')

const { formatNum } = require('../../utils/utils')
const { MYLIST } = require('../../utils/data')
const app = getApp()

Page({
    data: {
        userInfo: app.globalData.userInfo,
        currentAddress: app.globalData.currentAddress,
        activeUrl: 'index',
        actionsShow: false,
        actions: [
            { name: '便民信息', index: 0 },
            { name: '商业信息', index: 1 }
        ],
        actionsTcShow: false,

        swiperList: [],
        swiperList1: [],
        messageTypeList: [],
        merchantsTypeList: [],
        MYLIST: MYLIST,
        statisticsList: [],
        statisticsList1: [],
        hotlist: [],
        merchantsList: [],
        recotribelist: [],
        tribetopiclist: [],
        tabbarConf: {
            index: {
                loaded: true,
                num: 1,
              moreFlag: true,
                hasMore: true
            },
            merchants: {
                loaded: false,
                num: 1,
              moreFlag: true,
                hasMore: true
            },
            interactive: {
                loaded: false,
                num: 1,
              moreFlag: true,
                hasMore: true
            },
            my: {
                loaded: false,
                num: 1,
              moreFlag: true,
                hasMore: true
            }
        }
    },
    onLoad: function() {
        wx.setNavigationBarColor({
            frontColor: '#ffffff',
            backgroundColor: '#ff5801'
        })
        this.getInitData()
        app.setWatching('currentAddress', currentAddress => {
            this.setData({
                currentAddress
            })
        })
        app.setWatching('userInfo', userInfo => {
            this.setData({
                userInfo
            })
        })
    },

    onShareAppMessage: function(res) {
        if (res.from === 'button') {
            // 来自页面内转发按钮
            console.log(res.target)
        }
        return {
            title: '信息分类小程序',
            path: '/pages/index/index',
            success: function(res) {
                // 转发成功
            },
            fail: function(res) {
                // 转发失败
            }
        }
    },
    // 因为自定义了tabbar，所以四个一级页面初始化数据需要在一下四个方法里面分别获取
    getInitData() {
        // 首页广告轮播
        ad({ typeid: 1 }).then(res => {
            this.setData({
                swiperList: res
            })
        })
        // 首页分类icon信息
        messageType().then(res => {
            let data = res.map(item => {
                return Object.assign({}, item, {
                    text: item.title,
                    icon: item.typeimg,
                    path: '/pages/indexList/index',
                    data: item
                })
            })
            app.globalData.messageTypeList = data
            this.setData({
                messageTypeList: data
            })
        })
        // 首页信息浏览量
        statistics({ typeid: 1 }).then(res => {
            let statisticsList = [
                {
                    text: '信息浏览量',
                    num: formatNum(
                        res.message_readnum + res.message_shouReadnum
                    )
                },
                {
                    text: '发布信息',
                    num: formatNum(
                        res.message_fabunum + res.message_shouFabunum
                    )
                }
            ]

            this.setData({
                statisticsList
            })
        })
        this.indexGetInitData()
        // 商户页面广告
        ad({ typeid: 2 }).then(res => {
            app.globalData.swiperList1 = res
            this.setData({
                swiperList1: res
            })
        })
        // 商户页面浏览信息
        statistics({ typeid: 2 }).then(res => {
            let statisticsList1 = [
                {
                    text: '信息浏览量',
                    num: formatNum(
                        res.message_readnum + res.message_shouReadnum
                    )
                },
                {
                    text: '发布信息',
                    num: formatNum(
                        res.message_fabunum + res.message_shouFabunum
                    )
                }
            ]
            this.setData({
                statisticsList1
            })
        })
        merchantsType().then(res => {
            let data = res.map((item, index) => {
                return Object.assign({}, item, {
                    text: item.title,
                    icon: item.typeimg,
                    path: `/pages/merchantsList/index`,
                    data: item
                })
            })
            app.globalData.merchantsTypeList = data
            this.setData({
                merchantsTypeList: data
            })
        })

        addtype().then(res => {
            let data = res.map(item => {
                return Object.assign({}, item, {
                    text: item.title,
                    icon: item.typeimg
                })
            })
            app.globalData.addtype = data
        })
    },
    indexGetInitData() {
        // 首页列表
        hotlist({
            pageNumber: this.data.tabbarConf.index.num
        }).then(res => {
            this.stopRefreshFn({
              url:'index',
              list:res.list
            })
            if (this.data.tabbarConf.index.num == 1) {
                this.setData({
                    hotlist: []
                })
            }
            this.setData({
                hotlist: this.data.hotlist.concat(res.list)
            })
        })
    },
    merchantsGetInitData() {
        hotMerchants().then(res => {
          this.stopRefreshFn({
            url: 'merchants',
            list: res.list
          })
            if (this.data.tabbarConf.merchants.num == 1) {
                this.setData({
                    merchantsList: []
                })
            }
            this.setData({
                merchantsList: this.data.merchantsList.concat(res.list)
            })
        })
    },
    interactiveGetInitData() {
        recotribelist().then(res => {
            this.setData({
                recotribelist: res.splice(0, 4)
            })
        })
        tribetopiclist().then(res => {
          this.stopRefreshFn({
            url: 'interactive',
            list: res
          })
            if (this.data.tabbarConf.interactive.num == 1) {
                this.setData({
                    tribetopiclist: []
                })
            }
            this.setData({
                tribetopiclist: this.data.tribetopiclist.concat(res)
            })
        })
    },
    myGetInitData(obj) {

        this.stopRefreshFn({url:'my'})
    },
    actionsShowFn: function() {
        this.setData({
            actionsShow: !this.data.actionsShow
        })
    },
    tabbarTCClick: function() {
        this.setData({
            actionsTcShow: !this.data.actionsTcShow
        })
    },
    tabbarClick: function(e) {
        let { url, title } = e.currentTarget.dataset
        if (url === this.data.activeUrl) {
            return false
        }
        if (url === 'publishedIn') {
            this.actionsShowFn()
        } else {
            if (!this.data.tabbarConf[url].loaded) {
                this[url + 'GetInitData']()
            }
            var backgroundColor = '#ff5801'
            switch (url) {
                case 'index':
                    wx.setNavigationBarColor({
                        frontColor: '#ffffff',
                        backgroundColor: '#ff5801'
                    })
                    break
                case 'my':
                    wx.setNavigationBarColor({
                        frontColor: '#ffffff',
                        backgroundColor: '#ea9518'
                    })
                    break
                default:
                    wx.setNavigationBarColor({
                        frontColor: '#000000',
                        backgroundColor: '#fff'
                    })
                    break
            }
            let tabbarConf = this.data.tabbarConf
            tabbarConf[url].loaded = true
            this.setData({
                activeUrl: url,
                tabbarConf
            })

            wx.setNavigationBarTitle({
                title
            })
        }
    },
    onCloseTC() {
        this.tabbarTCClick()
    },
    onClose() {
        this.actionsShowFn()
    },

    onSelect(e) {
        let { index } = e.detail
        if (index === 0) {
            wx.navigateTo({
                url: '/pages/lawhall/index'
            })
        }
    },
    jumpToTenants() {
        wx.navigateTo({
            url: '/pages/lawhall/index?type=tenants'
        })
    },
    recotribeDetail() {
        // 部落详情
    },
    // 话题详情
    topicDetails(e) {
        let { id } = e.currentTarget.dataset
        wx.navigateTo({
            url: `/pages/topicDetails/index?id=${id}`
        })
    },
    recotribeMore() {
        console.log('hello')
        // 更多部落
        wx.navigateTo({ url: '/pages/tribalList/index' })
    },
    stopRefreshFn(obj) {
      if(obj.url != 'my'){
        let tabbarConf =  this.data.tabbarConf
          if(obj.list.length < 20){
            tabbarConf[obj.url].hasMore = false
          }else{
            tabbarConf[obj.url].hasMore = true
          }
          this.setData({
            tabbarConf
          })
      }
        wx.hideNavigationBarLoading()
        // 停止下拉动作
        wx.stopPullDownRefresh()
    },
    setLoadInfo(url) {
        let tabbarConf = this.data.tabbarConf

        tabbarConf[url].num = tabbarConf[url].num + 1
        tabbarConf[url].moreFlag = false
        this.setData({
            tabbarConf
        })
    },
    onPullDownRefresh: function() {
        let { activeUrl } = this.data
        wx.showNavigationBarLoading()
        let tabbarConf = this.data.tabbarConf
      tabbarConf[activeUrl].num = 1
        this.setData({
            tabbarConf
        })

        this[activeUrl + 'GetInitData']()
    },
    onReachBottom: function() {
        let { activeUrl } = this.data
      console.log(this.data.tabbarConf[activeUrl])
        if (
            this.data.tabbarConf[activeUrl].hasMore &&
            this.data.tabbarConf[activeUrl].moreFlag
        ) {
            this.setLoadInfo(activeUrl)
            this[activeUrl + 'GetInitData']()
        }
    }
})
